package cn.nawang.ebeim.api.repository.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;

import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import cn.nawang.ebeim.api.bean.ClassBean;
import cn.nawang.ebeim.api.comm.BaseQuery;
import cn.nawang.ebeim.api.comm.PageList;
import cn.nawang.ebeim.api.comm.Pages;
import cn.nawang.ebeim.api.domain.BackupLog;
import cn.nawang.ebeim.api.domain.PushMessage;
import cn.nawang.ebeim.api.utils.DateOperate;
import cn.nawang.ebeim.api.utils.DateUtils;
import cn.nawang.ebeim.api.utils.RefectSql;

/**
 * @ClassName: BackupLogQueryRepositoryImpl
 * @Description: 备份日志dao层
 * @author 张建峰
 * @date 2015年9月22日14:35:25
 * @version v1.0
 */
@Repository
public class BackupLogQueryRepositoryImpl extends BaseQuery {

  @Autowired
  private EntityManagerFactory entityManagerFactory;

  /**
   * @author 张建峰
   * @Description: 根据某个属性查询列表
   * @param @param property
   * @param @param value
   * @param @return
   * @return List<Datasource>
   * @date 2015年9月22日14:35:41
   *
   * @修改人 张建峰
   * @修改日期
   */
  public List<BackupLog> findByParam(String property, Object value) {
    List objList = null;
    String sql = "from BackupLog obj where obj." + property + " = ?1";
    EntityManager em = entityManagerFactory.createEntityManager();
    try {      
      Query query = em.createQuery(sql);
      query.setParameter(1, value);
      objList = query.getResultList();
    } catch (Exception ex) {
      ex.printStackTrace();
    }finally{
      em.close();
    }
    return objList;
  }

  /**
   * @author 张建峰
   * @Description: 分页查询
   * @param @param b
   * @param @param page
   * @param @return
   * @return PageList
   * @date 2015年9月22日下午2:40:00
   *
   * @修改人 张建峰
   * @修改日期
   */
  public PageList findByPage(BackupLog backupLog, Pages page) {
    PageList pl = null;
    String sql = "from BackupLog obj where '1'='1'";
    List<ClassBean> conditions = RefectSql.getClassBeans(backupLog);
    List<Object> paramsList = new ArrayList<Object>();
    for (int i = 0; i < conditions.size(); i++) {
      ClassBean classBean = conditions.get(i);
      if (classBean.getContent() != null) {
        sql += " and obj." + classBean.getName() + "= ?";
        paramsList.add(classBean.getContent());
      }
    }
    sql += " order by obj.endTime desc";

    int count = this.countData(sql, paramsList);
    page.setTotalRecord(count);
    page.setTotalPage((int) Math.ceil((count * 1.0) / page.getPageSize()));
    EntityManager em = entityManagerFactory.createEntityManager();
    try {      
      Query query = em.createQuery(sql);
      query.setFirstResult(page.getStartPos());
      query.setMaxResults(page.getPageSize());
      for (int i = 0; i < paramsList.size(); i++) {
        query.setParameter(i + 1, paramsList.get(i));
      }
      List objList = query.getResultList();
      pl = new PageList();
      pl.setObjList(objList);
      pl.setPage(page);
      pl.setSuccess(true);
    } catch (Exception ex) {
      ex.printStackTrace();
    }finally{
      em.close();
    }
    return pl;
  }

  public List<BackupLog> findByBackupLog(BackupLog backupLog) {
    List<BackupLog> logs = null;
    String sql = "from BackupLog obj where '1'='1'";
    List<ClassBean> conditions = RefectSql.getClassBeans(backupLog);
    List<Object> paramsList = new ArrayList<Object>();
    for (int i = 0; i < conditions.size(); i++) {
      ClassBean classBean = conditions.get(i);
      if (classBean.getContent() != null) {
        sql += " and obj." + classBean.getName() + "= ?";
        paramsList.add(classBean.getContent());
      }
    }
    EntityManager em = entityManagerFactory.createEntityManager();
    try {
      
      Query query = em.createQuery(sql);
      for (int i = 0; i < paramsList.size(); i++) {
        query.setParameter(i + 1, paramsList.get(i));
      }
      logs = query.getResultList();
    } catch (Exception ex) {
      ex.printStackTrace();
    }finally{
      em.close();
    }
    return logs;
  }

  /**
   * @author 张建峰
   * @Description: 根据sql查询count
   * @param @param sql
   * @param @return
   * @return int
   * @date 2015年9月22日14:39:25
   *
   * @修改人 张建峰
   * @修改日期
   */
  public int countData(String sql, List<Object> paramsList) {
    EntityManager em = entityManagerFactory.createEntityManager();
    int count=0;
    try {     
      Query query = em.createQuery(sql);
      for (int i = 0; i < paramsList.size(); i++) {
        query.setParameter(i + 1, paramsList.get(i));
      }
      count = query.getResultList().size();
      return count;
    } catch (Exception ex) {
      ex.printStackTrace();
    }finally{
      em.close();
    }
    return count;
  }

  /**
   * 
   * @author fanyb
   * @Description: 根据ds_id和status获取列表 并对end_time进行排序，时间越大，排越前。
   * @param dsId
   * @param status
   * @return
   * List<BackupLog> 
   * @date Sep 29, 20159:04:12 AM
   *
   * @修改人 
   * @修改日期
   */
  public PageList findByDsIdAndStatus(Pages page) {
    String hqlCount = "select count(bl.id) from BackupLog bl where 1=1 ";
    String hqlList="select bl from BackupLog bl where 1=1 ";
    String order=" order by bl.beginTime desc";
    PageList pl = null;
    try{
      String cod = joinSearchCondition(page);//拼接查询条件
      pl = queryListByPaging(hqlCount+cod+order, hqlList+cod+order, page);
    }catch (Exception ex) {
      ex.printStackTrace();
    }
    return pl;
  }
  /**
   * 
   * @author: huanghj
   * @Description: 获得用户当天的备份次数
   * @param @return
   * @return int 
   * @date 2015年10月24日上午11:16:15
   *
   * @修改人 
   * @修改日期
   */
  public int getTodayBackupTimes(String userId)
  {
    long start=DateOperate.getTime(0, 0, 0);
    long end=DateOperate.getTime(23, 59, 59);
    StringBuffer sb=new StringBuffer();
    sb.append(" select COUNT(1) as backup_count from tb_backup_log ");
    sb.append(" where ds_id in (select id from tb_datasource where create_user_id ='"+userId+"')");
    sb.append(" and begin_time >").append(start);
    sb.append(" and begin_time<").append(end);
    List<Map> obj=find(sb.toString());
    if (obj != null && obj.size() > 0)
      return Integer.valueOf(obj.get(0).get("backup_count").toString());
    return 0;
  }
  
  public List find(String sql) {
    List<Map> objList = null;
    EntityManager em = entityManagerFactory.createEntityManager();
    try {
      Query query = em.createNativeQuery(sql);
      query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
      objList = query.getResultList();
    } catch (Exception ex) {
      ex.printStackTrace();
    } finally {
      em.close();
    }
    return objList;
  }
  
  /**
   * 
   * @author fanyb
   * @Description: 查找数据保险箱最新更新时间
   * @param dsType
   * @param createUserId
   * @return String 
   * @date Nov 12, 20157:48:16 PM
   *
   * @修改人 
   * @修改日期
   */
  public String findByDsTypeAndCreateUserId(String dsType,String createUserId) {
    String hqlList="select bl from BackupLog bl,Datasource d where "
        + "d.dsType=:dsType and d.createUserId=:createUserId and bl.dsId=d.id ";
    String order=" order by bl.beginTime desc";
    List<BackupLog> pl = null;
    Map<String, Object> paraMap = new HashMap<String, Object>();
    try {
      paraMap.put("dsType", dsType);
      paraMap.put("createUserId", createUserId);
      pl = queryObject(hqlList + order, paraMap);
      if (!pl.isEmpty() && pl != null) {
        return DateUtils.longTime2String(pl.get(0).getBeginTime());
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return "-";
  }
}
